<?php
/**
 * @ClassName: Storeregion
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-13 15:19
 * @Version: V1.0.0
 */

namespace app\api\controller\merchant;

use app\api\controller\Api;
use app\common\model;

class Storeregion extends Api
{
    /**
     * 客户列表
     * @return \think\response\Json
     */
    function getCustomerList()
    {
        $keyword = input('keyword', '');
        $store_id = input('store_id', 0);
        $region_id = input('region_id', 0);
        $type = input('type', 0);
        $skip = input('skip', 0);
        $limit = input('limit', 20);

        $customer_ids = [];
        $region = model\StoreRegion::get($region_id);
        if ($region) {
            $customer_ids = stringToArray($region['customer_ids']);
        }

        $where = [
            ['c.status', '=', 1],//客户状态
            ['cs.store_id', '=', $store_id],//店铺
        ];

        if ($keyword) {
            $where[] = ['c.customer_name|c.address', 'like', "%{$keyword}%"];
        }

        if ($type == 0) {
            // 本区域客户
            $customer_list = model\Customer::alias('c')
                ->leftJoin('customer_store cs', 'c.id=cs.customer_id')
                ->where($where)->where('c.id', 'in', $customer_ids)
                ->distinct('c.id')
                ->field("c.*,true as checked")->order('c.update_time desc')
                ->limit($skip, $limit)
                ->select();
        } else {
            // 非本区域客户
            $customer_list = model\Customer::alias('c')
                ->leftJoin('customer_store cs', 'c.id=cs.customer_id')
                ->where($where)->where('c.id', 'not in', $customer_ids)
                ->distinct('c.id')
                ->field("c.*,false as checked")->order('c.update_time desc')
                ->limit($skip, $limit)
                ->select();
        }

        $sql = model\Customer::getLastSql();
//       var_dump($sql);

        foreach ($customer_list as &$v) {
            //头像
            if ($v['avatar']) {
                $v['avatar'] = replace_url($v['avatar']);
            } else {
                $v['avatar'] = replace_url('/static/images/logo.png');
            }
        }

        $result = [
            'data' => $customer_list,
            'is_more' => count($customer_list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    function addCustomer(){
$region_id = input('id', 0);
    }

    function delCustomer(){
        $region_id = input('id', 0);
    }

}